package com.he.algorithm.order;

import java.util.Arrays;

/**
 * @description: 冒泡排序
 * @Author: HCL
 * @Date: 2024/9/3 9:52
 */
public class BubbleSort {

    public static void sort(int[] nums) {
        for (int i = 0; i < nums.length - 1; i++) {
            boolean exchange = false;
            for (int j = 0; j < nums.length - i - 1; j++) {//减去已经确定位置的元素
                if (nums[j] > nums[j + 1]) {
                    int temp = nums[j];
                    nums[j] = nums[j + 1];
                    nums[j + 1] = temp;
                    exchange = true;
                }
            }
            if (!exchange) {
                break;
            }
        }
    }

    public static void main(String[] args) {
        int[] nums = {7, 1, 3, 9, 5, 2, 6};
        /**
         * 比较6次
         * 0和1比 1 7 3 9 5 2 6
         * 1和2比 1 3 7 9 5 2 6
         * 2和3比 1 3 7 9 5 2 6
         * 3和4比 1 3 7 5 9 2 6
         * 4和5比 1 3 7 5 2 9 6
         * 5和6比 1 3 7 5 2 6 9
         *
         *
        */


        sort(nums);
        System.out.println(Arrays.toString(nums));
    }
}
